package cn.chenxinjie.hrm.service.impl;

import cn.chenxinjie.hrm.constant.UserConstants;
import cn.chenxinjie.hrm.domain.LoginUser;
import cn.chenxinjie.hrm.domain.VipUser;
import cn.chenxinjie.hrm.dto.RegisterDto;
import cn.chenxinjie.hrm.feign.LoginUserFeign;
import cn.chenxinjie.hrm.mapper.VipUserMapper;
import cn.chenxinjie.hrm.service.IVipUserService;
import cn.chenxinjie.hrm.util.AjaxResult;
import cn.chenxinjie.hrm.util.BitStatesUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * 会员登录账号 服务实现类
 *
 * @author chenxinjie
 * @since 2022-03-18
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;
    @Autowired
    private LoginUserFeign loginUserFeign;

    @Override
    public AjaxResult register(RegisterDto dto) {
        // 获取对象中的参数
        String mobile = dto.getMobile();
        String smsCode = dto.getSmsCode();
        String password = dto.getPassword();
        // 校验短信验证码
        Object o = redisTemplate.opsForValue().get(UserConstants.USER_REGISTER + mobile);
        Assert.notNull(o,"验证码已经过期,请重新获取");
        Assert.isTrue(dto.getSmsCode().equals(o.toString()),"验证码错误,请重新输入");
        // 保存到auth服务中的t_login_user表,返回自增主键
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(mobile);
        loginUser.setPassword(password);
        AjaxResult result = loginUserFeign.register(loginUser);
        Assert.isTrue(result.isSuccess(),"保存失败");
        // 获取到loginUser的id
        Long loginUserId = Long.valueOf((Integer) result.getResultObj());
        // 保存t_vip_user信息
        VipUser vipUser = new VipUser();
        vipUser.setLoginId(loginUserId);
        vipUser.setPhone(mobile);
        vipUser.setCreateTime(System.currentTimeMillis());
        vipUser.setPassword(password);
        // 状态使用位状态来保存
        long state = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        state = BitStatesUtils.addState(state, BitStatesUtils.OP_AUTHED_PHONE);
        vipUser.setBitState(state);
        vipUserMapper.insert(vipUser);
        return result;
    }


}
